package com.dmwork.service.customer.controller.sms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dmwork.common.base.result.R;
import com.dmwork.common.base.result.ResultCodeEnum;
import com.dmwork.service.base.exception.DmworkException;
import com.dmwork.service.customer.entity.Customer;
import com.dmwork.service.customer.entity.vo.SmsVo;
import com.dmwork.service.customer.service.CustomerService;
import com.dmwork.service.customer.service.SmsService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/front/dm_work/customer/sms")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("为指定的号码发送短信")
    @PostMapping("send_verification_code/{type}")
    public R sendVerificationCode(@PathVariable Integer type, @RequestBody SmsVo smsVo) {

        int count = customerService.count(new QueryWrapper<Customer>().eq("mobile", smsVo.getPhoneNumber()));
        switch (type) {
            case 0: //type==0，是在注册时发送验证码
                if (count==0) {
                    return sendMessage(smsVo.getPhoneNumber());
                }else {
                    return R.error().message("该手机号已被注册");
                }
            case 1: //type==1，是在修改密码时发送验证码
                //验证该号码是否已注册
                if (count>0) {
                    return sendMessage(smsVo.getPhoneNumber());
                }else {
                    return R.error().message("该手机号未注册");
                }
            default:
                return R.error().message("请指定范围内的type");
        }

    }

    @ApiOperation("对输入的验证码进行验证")
    @PostMapping("check_verification_code")
    public R checkVerificationCode(@RequestBody SmsVo smsVo) {
        Object o = redisTemplate.opsForValue().get(smsVo.getPhoneNumber());
        if (o != null) {
            String code= (String) o;
            if (code.equals(smsVo.getVerificationCode())) {
                return R.ok().message("验证码正确");
            }else {
                throw new DmworkException(ResultCodeEnum.VERIFICATION_CODE_WRONG);
            }
        }else {
            throw new DmworkException(ResultCodeEnum.VERIFICATION_CODE_EMPTY_OR_NULL);
        }
    }

    /**
     * 发送短信的私有方法封装
     * @param phoneNumber 发送的目标手机号
     * @return 发送的结果
     */
    private R sendMessage(String phoneNumber) {
        if (smsService.sendSms(phoneNumber)) {
            return R.ok().message("发送成功");
        } else {
            return R.error().message("发送失败");
        }
    }


}
